package com.guan.ruiji.controller;

import com.guan.ruiji.common.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

/**
 * @author guanzhenjie
 */
@RestController
@RequestMapping("common")
public class CommonController {

    private String imgPath;

    @RequestMapping("upload")
    public R<String> upload(MultipartFile file){
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString() + suffix;

        ApplicationHome applicationHome = new ApplicationHome(this.getClass());
        this.imgPath = applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath() + "/src/main/resources/static/images/";

        File dir = new File(imgPath);
        if (!dir.exists()) {
            dir.mkdir();
        }
        try{
            file.transferTo(new File(imgPath + fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }

        return R.success(fileName);
    }

    @RequestMapping("download")
    public void download(String name, HttpServletResponse response) {
        response.setContentType("image/jpeg");
        FileInputStream fileInputStream = null;
        ServletOutputStream outputStream = null;
        try {
            fileInputStream = new FileInputStream(new File(imgPath + name));

            outputStream = response.getOutputStream();

            int length = 0;
            byte[] bytes = new byte[1024];
            while((length = fileInputStream.read(bytes)) != -1){
                outputStream.write(bytes, 0, length);
                outputStream.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
